package com.study.juc.atomics;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: juc-study
 * @author: jzhou
 * @date: 2022-08-16 19:05
 * @version: 1.0
 * @description: 主要演示countDownLatch
 **/
public class AtomicIntegerDemo {
	public static int SIZE = 50;
	public static void main(String[] args) throws InterruptedException {
		MyNumber myNumber = new MyNumber();
		CountDownLatch countDownLatch = new CountDownLatch(SIZE);
		for (int i = 1; i <= SIZE; i++) {
			new Thread(() -> {
				try {
					for (int j = 1; j <= 1000; j++) {
						myNumber.addPlusPlus();;
					}
				}finally {
					countDownLatch.countDown();
				}

			},String.valueOf(i)).start();
		}
		countDownLatch.await();
		//当主线程结束时，计算线程还没有结束，不是最终结果，必须要等待上面50个线程计算完成
		System.out.println(Thread.currentThread().getName() +"\t"+ myNumber.atomicInteger.get());
	}
}

class MyNumber{
	AtomicInteger atomicInteger = new AtomicInteger();

	public void addPlusPlus(){
		atomicInteger.getAndIncrement();
	}
}